package main.java.tmi.order.web;

import java.sql.SQLException;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import main.java.tmi.common.service.UserVO;
import main.java.tmi.order.service.OrderService;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;


/**
 *  Controller
 *
 * @author ssong
 * @since 2012.04.01
 */
@Controller
public class OrderController {

    @Resource(name = "orderServiceImpl")
    private OrderService orderService;

    /**
     * The Constructor
     */
    public OrderController() {
        //logger = LogFactory.getLog(this.getClass());
    }

    /**
     * 
     * 폼 호출
     * @param HttpServletResponse response
     * @param ModelMap model
     * @return
     * @throws SQLException
     */
    @RequestMapping("/orderForm")
    public String view(HttpServletRequest request, HttpServletResponse response, ModelMap model) throws SQLException {
        System.out.println("=======================> orderForm Start");

        return "/tmi/order/order";
    }

    /**
     * ordSeq값 가져오기
     */
    @RequestMapping("/getMaxOdrSeq")
    public void getMaxOdrSeq(@RequestParam Map param, Model model) throws Exception {
    	System.out.println("=======================> addAction param : "+param);
    	String ordNo2="";
    	try{
    		ordNo2  = orderService.getMaxOdrSeq(param.get("ordNo1").toString()) ;
    	}catch (Exception e){
    		//화면단에서 잡아줘야 하므로 별도 필요없음.
    	}
    	model.addAttribute("ordNo2",ordNo2);
    }
    
    
    /**
     * order SAVE
     */
    @RequestMapping("/saveOrder")
    public void saveOrder(@RequestParam Map param, Model model , HttpServletRequest request) throws Exception {
    	System.out.println("=======================> saveOrder Start");
    	
    	UserVO userInfo = (UserVO) RequestContextHolder.getRequestAttributes().getAttribute("userInfo", RequestAttributes.SCOPE_SESSION);
    	param.put("sesseionId", userInfo.getUserId());
    	System.out.println("sesseionId============> "+userInfo.getUserId());
    	
    	String saveStatus = param.get("saveStatus").toString();
    	System.out.println("=======================> saveStatus"+saveStatus);
    	
    	if(saveStatus.equals("SAVE")){
    			String dupChk = orderService.orderDupChk(param.get("ordNo1").toString());
    			if(dupChk.equals("Y")){
    				orderService.addOrder(param , request);
    			}else{
    				model.addAttribute("resultDup",dupChk);
    			}
    	}else if(saveStatus.equals("UPDATE")){
        	model.addAttribute("result", orderService.modifyOrder(param , request) );
    	}

        //저장 완료 후 조회
		model.addAttribute("resultMap",orderService.getOrderView(param));
		model.addAttribute("resultDetailList",orderService.getOrderDetailList(param));
		model.addAttribute("result",true);
    }
    
    /**
     * order SAVE
     */
    @RequestMapping("/deleteOrder")
    public void deleteOrder(@RequestParam Map param, Model model , HttpServletRequest request) throws Exception {
    	System.out.println("=======================> deleteOrder Start");
    	
		model.addAttribute("result",orderService.deleteOrder(param));
    }
    
    /* ========================= ORDER DETAIL =========================*/        
    
    /**
     * 조회
     */
    @RequestMapping("/getOrderView")
    public void getOrderView(@RequestParam Map param, Model model) throws Exception {
        System.out.println("=======================> getOrderView start");

        //저장 완료 후 조회
		model.addAttribute("resultMap",orderService.getOrderView(param));
		model.addAttribute("resultDetailList",orderService.getOrderDetailList(param));
    }
    
    /**
     * 삭제
     */
    @RequestMapping("/delOdrDetail")
    public void delOdrDetail(@RequestParam Map param, Model model) throws Exception {
        System.out.println("=======================> delOdrDetail Start");
        model.addAttribute("result", orderService.delOdrDetail(param) );
    }

    
    /**
    * 수정
    */
    @RequestMapping("/detailUpdate")
    public void detailUpdate(@RequestParam Map param, Model model) throws Exception {
        System.out.println("=======================> detailUpdate Start");
    	UserVO userInfo = (UserVO) RequestContextHolder.getRequestAttributes().getAttribute("userInfo", RequestAttributes.SCOPE_SESSION);
    	param.put("sesseionId", userInfo.getUserId());
    	System.out.println("sesseionId============> "+userInfo.getUserId());
    	
        model.addAttribute("result", orderService.detailUpdate(param) );
    }
    

    /* ========================= ORDER Division =========================*/
    
    @RequestMapping("/getMaxOrdPseq")
    public void getMaxOrdPseq(@RequestParam Map param, Model model) throws Exception {
        System.out.println("=======================> getMaxOrdPseq param : "+param);
        String confMaxOrdPseq="";
        try{
            confMaxOrdPseq  = orderService.getMaxOrdPseq(param) ;
        }catch (Exception e){
            //화면단에서 잡아줘야 하므로 별도 필요없음.
        }
        model.addAttribute("confMaxOrdPseq",confMaxOrdPseq);
    }
    
    /**
     * 조회
     */
    @RequestMapping("/getOrderDivisionList")
    public void getOrderDivisionList(@RequestParam Map param, Model model) throws Exception {
        System.out.println("=======================> getOrderDivisionList start");
        
        System.out.println("=======================> TYPE : " + param.get("type"));

        if( param.get("type").equals("DEFAULT") ){
            System.out.println("=======================> getMaxOrdPseq start");
            
            String confMaxOrdPseq  = orderService.getMaxOrdPseq(param) ;
            model.addAttribute("resultConfMaxOrdPseq",confMaxOrdPseq);
            
            System.out.println("=======================> getMaxOrdPseq  = "+ confMaxOrdPseq);
            
            if(confMaxOrdPseq.equals("0")){
                model.addAttribute("resultDivisionList",orderService.getDefaultOrderDivisionList(param));
            }else{
                param.put("confMaxOrdPseq" , confMaxOrdPseq); 
                model.addAttribute("resultDivisionList",orderService.getLastOrderDivisionList(param));
            }
        }else{
            model.addAttribute("resultDivisionList",orderService.getNewOrderDivisionList(param));
            model.addAttribute("resultConfMaxOrdPseq","NEW");
        }
        
        model.addAttribute("type","SEARCH");  //화면단 컨트롤시
    }
    
    
    /**
     * save
     */
    @RequestMapping("/actionOrderDivision")
    public void actionOrderDivision(@RequestParam Map param, Model model , HttpServletRequest request) throws Exception {
        System.out.println("=======================> actionOrderDivision Start");
        boolean result = true;
        
        
        UserVO userInfo = (UserVO) RequestContextHolder.getRequestAttributes().getAttribute("userInfo", RequestAttributes.SCOPE_SESSION);
        param.put("sesseionId", userInfo.getUserId());
        System.out.println("sesseionId============> "+userInfo.getUserId());
        
        String btnType = param.get("btnType").toString();
        System.out.println("=======================> btnType : "+ param.get("btnType"));
                
        if(btnType.equals("INSERT")){
                orderService.addOrderDivisionDetail(param , request);
                
                String confMaxOrdPseq  = orderService.getMaxOrdPseq(param) ;
                
                model.addAttribute("resultDivisionList",orderService.getNewOrderDivisionList(param));
                model.addAttribute("resultConfMaxOrdPseq",confMaxOrdPseq);  //화면단 컨트롤시 MAX값 필요
                model.addAttribute("type","SAVE");  //화면단 컨트롤시
                
        }else if(btnType.equals("UPDATE")){
                orderService.modifyOrderDivisionDetail(param , request);
                
                param.put("confMaxOrdPseq",param.get("confOrdPseq"));
                model.addAttribute("resultDivisionList",orderService.getLastOrderDivisionList(param));
                model.addAttribute("resultConfMaxOrdPseq",param.get("confOrdPseq"));  //화면단 컨트롤시 MAX값 필요
                model.addAttribute("type","UPDATE");  //화면단 컨트롤시
        }else if(btnType.equals("DELETE")){
        	
        	result = orderService.deleteOrderDivisionDetail(param);
        	
        	if(result == true){
	        	String confMaxOrdPseq  = orderService.getMaxOrdPseq(param) ;
	        	
	        	param.put("confMaxOrdPseq", confMaxOrdPseq);
	            model.addAttribute("resultDivisionList",orderService.getLastOrderDivisionList(param));
	            model.addAttribute("resultConfMaxOrdPseq",confMaxOrdPseq);  //화면단 컨트롤시 MAX값 필요
	            model.addAttribute("type","DELETE");  //화면단 컨트롤시
        	}
        }

        model.addAttribute("result",result);
    }
    
    

    /**
     * 상단 버튼 조회
     */
    @RequestMapping("/searchOrderDivisionList")
    public void searchOrderDivisionList(@RequestParam Map param, Model model) throws Exception {
        System.out.println("=======================> searchOrderDivisionList start");

        model.addAttribute("resultDivisionList",orderService.getLastOrderDivisionList(param));
        model.addAttribute("resultConfSearchOrdPseq",param.get("confMaxOrdPseq"));  //화면단 컨트롤시 MAX값 필요
        model.addAttribute("resultConfMaxOrdPseq",param.get("realConfOrdPseq"));  //화면단 컨트롤시 MAX값 필요
        model.addAttribute("type","TOPSEARCH");  //화면단 컨트롤시
    }
    
    
}
